/*
 * 地图信息
 * @returns
 */
var defaultEventIcon = "../img/defaultEventType.png";
var defaultTVIcon = "../img/defaultTV.png";
var defaultPartIcon = "../img/defaultPart.png";
var allIds = [];
var arcGisUrl = "http://39.107.125.44:6080";
var map;
var toolbar;
var partLayer;
var centerX = 106.53884704455731;// 120.206354450751;
var centerY = 29.7219072675705;// 30.0725834699399;
var currentGraphic;
var drawHandler;
var dynamicTowPointFiveD;
var extendScal = 10;

var reportPointType = "reportPointType";
var registerPointType = "registerPointType";
var reportFlickerPointType = "reportFlickerPointType";
var registerFlickerPointType = "registerFlickerPointType";

var showPointType = reportPointType;
var showFlickerPointTyp = reportFlickerPointType;

var hidePointType = registerPointType;
var hideFlickerPointTyp = registerFlickerPointType;

var newTempId = "registerTempId";
var flickerPointID = "flickerPointID";
var secondLayer;

var vec;
var veca;

require(
		[ "esri/map", "esri/Color", "esri/graphic", "esri/InfoTemplate",
				"esri/SpatialReference", "esri/renderers/HeatmapRenderer",
				// 控件
				"esri/dijit/OverviewMap", "esri/dijit/Scalebar",
				"esri/dijit/Measurement", "esri/units",
				// 图层
				"tdlib/TDTLayer", "tdlib/TDTAnnoLayer", "tdlib/TDT_ImgLayer",
				"tdlib/TDT_ImgAnnoLayer", "esri/layers/GraphicsLayer",
				"esri/layers/ArcGISDynamicMapServiceLayer",
				"esri/layers/ArcGISTiledMapServiceLayer",
				"esri/layers/FeatureLayer",
				// 图形要素
				"esri/geometry/Point", "esri/geometry/Polyline",
				"esri/geometry/Polygon", "esri/geometry/Circle",
				// 样式
				"esri/symbols/TextSymbol", "esri/symbols/SimpleMarkerSymbol",
				"esri/symbols/PictureMarkerSymbol",
				"esri/symbols/SimpleLineSymbol",
				"esri/symbols/SimpleFillSymbol",
				// 标签
				"esri/symbols/Font", "esri/layers/LabelClass",
				// 查询
				"esri/tasks/query", "esri/tasks/QueryTask",
				"esri/toolbars/draw", "esri/dijit/Popup",
				"esri/dijit/PopupTemplate", "dojo/dom", "dojo/dom-construct" ],
		function(Map, Color, Graphic, InfoTemplate, SpatialReference,
				HeatmapRenderer, OverviewMap, Scalebar, Measurement, Units,
				TDTLayer, TDTAnnoLayer, TDT_ImgLayer, TDT_ImgAnnoLayer,
				GraphicsLayer, ArcGISDynamicMapServiceLayer,
				ArcGISTiledMapServiceLayer, FeatureLayer, Point, Polyline,
				Polygon, Circle, TextSymbol, SimpleMarkerSymbol,
				PictureMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, Font,
				LabelClass, Query, QueryTask, Draw, Popup, PopupTemplate, dom,
				domConstruct) {

			map = new Map("map", {
				slider : false,
				logo : false,
				showLabels : true,
				center : [ centerX, centerY ],
				zoom : 17,
				minZoom : 8
			});

			// 初始化比例尺
			var scalebar = new Scalebar({
				map : map,
				attachTo : "bottom-left",
				scalebarUnit : "dual",
			});

			// 显示比例尺
			scalebar.show();
			drawHandler = Draw;
			vec = new TDTLayer();// 切片线画图
			veca = new TDTAnnoLayer();// 切片标注
			var img = new TDT_ImgLayer();
			var imga = new TDT_ImgAnnoLayer();
			map.addLayer(vec);
			map.addLayer(veca);

			dynamicTowPointFiveD = new ArcGISTiledMapServiceLayer(arcGisUrl
					+ "/arcgis/rest/services/YuelaiMap/MapServer");
			//dynamicTowPointFiveD.hide();
			dynamicTowPointFiveD.id = "dynamicTowPointFiveD";
			map.addLayer(dynamicTowPointFiveD);
			dynamicTowPointFiveD.hide();
			var url = arcGisUrl + "/arcgis/rest/services/ceshi2/MapServer";
			secondLayer = new FeatureLayer(url + "/15", {
				mode:FeatureLayer.MODE_SNAPSHOT,
				outFields : [ "*" ],
				maxScale : 0,
				minScale : 4508.935440959931,
				visible : true,
				id : "secondLayer"
			});
			map.addLayer(secondLayer);

			secondLayer.setMaxScale(0);
			secondLayer.setMinScale(4508.935440959931);

			map.graphics
					.on(
							"mouse-down",
							function(evt) {
								console.log("graphicslayer:mouse-down");
								if (evt.graphic
										&& (evt.graphic.pointType == reportPointType || evt.graphic.pointType == flickerPointType)) {
									currentGraphic = evt.graphic;
								} else {
									currentGraphic = null;
								}
								if (currentGraphic) {
									currentGraphic.isMouseDown = true;
									getEventReport(evt.graphic.attributes);
									getProcedure(evt.graphic.attributes.id);
								}
							});

			// map.on("mouse-drag", function(evt) {
			// console.log("map:mouse-drag");
			// if (currentGraphic) {
			// if (currentGraphic.isMouseDown) {
			// currentGraphic.setGeometry(evt.mapPoint);
			//
			// // 同步移动报警点
			// var geometry = flickerPoint.geometry;
			// geometry.x = evt.mapPoint.x;
			// geometry.y = evt.mapPoint.y;
			// flickerPoint.setGeometry(geometry);
			// }
			// }
			//
			// });

			map.on("mouse-up", function(evt) {
				console.log("map:mouse-up");
				if (currentGraphic) {
					map.enableMapNavigation();
					map.enablePan();
					currentGraphic.isMouseDown = false;
					console.log(currentGraphic.attributes.id);
					var currentGraphicTemp = currentGraphic;
					currentGraphic = null;

				}

			});

			toolbar = new Draw(map);
			dojo.connect(toolbar, "onDrawEnd");
			//getReportData();
			// getEventReportData($("#eventReportIdentify").val(), $(
			// "#eventRegisterIdentify").val());
			/* $('body').everyTime('1s',test); */

			// return;
			// 防异步错误
			clearInterval(flashTime);
			// 单位数据刷新
			var flashTime = setInterval(function() {
				refreashFlickerPoint();
			}, 75);
			initPage();
		});

function refreashFlickerPoint() {
	var len = map.graphics.graphics.length;
	var graphics = map.graphics.graphics;
	for (var i = 0; i < len; i++) {
		var graphic = graphics[i];
		if (graphic.pointType == showFlickerPointTyp ) {
			var symbol = graphic.symbol;
			if (symbol) {
				symbol.color.a -= 0.05;
				symbol.setSize(symbol.size + 8);

				if (symbol.color.a <= 0) {
					symbol.color.a = 1;
					symbol.setSize(1);
				}
				graphic.setSymbol(symbol);
			}
		}
	}
}

function getReportData() {
	$.ajax({
		url : rootPath + "/ui/eventReport/getReports/初始化",
		dataType : 'json',
		data : "",
		type : 'post',
		contentType : "application/json",
		success : function(result) {
			var len = result.reports.length;
			for (var i = 0; i < len; i++) {
				var report = result.reports[i];
				//allIds.push(report.id);
				var iconAddress = "";
				if (report.reportEventType
						&& report.reportEventType.iconAddress
						&& report.reportEventType.iconAddress != "") {
					iconAddress = window.rootPath + "/"
							+ report.reportEventType.iconAddress;
				}
				;
				createFlickerPoint(report);
				createPoint(report, iconAddress, reportPointType);
			}
		}
	});
}

// 创建点
function createPoint(data, symbolurl, pointType) {
	if (symbolurl == "" ) {
		symbolurl = defaultEventIcon;
	}
	
	var symbol = new esri.symbol.PictureMarkerSymbol(symbolurl, 20, 20);
	var myPoint = {
		"geometry" : {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		},
		"attributes" : data,
		"symbol" : symbol
	};
	var graphic = getcurrentGraphic(data.id, pointType);
	if (graphic == null) {
		graphic = new esri.Graphic(myPoint);
		graphic.symbol = symbol;
		graphic.attributes = data;
		graphic.pointType = pointType;
		
		map.graphics.add(graphic);
		
	} else {
		var geometry = graphic.geometry;
		geometry.x = data.longitude;
		geometry.y = data.latitude;

		graphic.attributes = data;
		graphic.pointType = pointType;
		graphic.setGeometry(geometry);
		graphic.setSymbol(symbol);
	}
	
	if(pointType == showPointType){
		graphic.show();
	}else{
		graphic.hide();
	}
	return graphic;
};

function setCenter(data) {
	var id=data.id;
//	var graphic = getcurrentGraphic(id, showPointType);
	var graphic = getcurrentGraphicByShow(id, showFlickerPointTyp);
	map.centerAndZoom(graphic.geometry, map.getLevel());
}

function getPointSymbol(type){
	var symbol;
	if(type == 'show'){
		symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, // 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
				1, // 像素
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID, // 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
						new dojo.Color([ 0, 0, 255 ]), 0.1), // 颜色 1 // 像素 ),
				new dojo.Color([ 0, 0, 255, 1 ]) // 颜色和透明度
		);
	}else if(type == reportFlickerPointType){
		symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, // 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
				1, // 像素
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID, // 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
						new dojo.Color([ 255, 0, 0 ]), 0.1), // 颜色 1 // 像素 ),
				new dojo.Color([ 255, 0, 0, 1 ]) // 颜色和透明度
		);
	}else{
		symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, // 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
				1, // 像素
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID, // 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
						new dojo.Color([ 255, 255, 0 ]), 0.1), // 颜色 1 // 像素 ),
				new dojo.Color([ 255, 255, 0, 1 ]) // 颜色和透明度
		);
	}
	return symbol;
}

function createFlickerPoint(data,pointType) {
	var symbol;
	
	if(pointType == reportFlickerPointType){
		symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, // 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
				1, // 像素
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID, // 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
						new dojo.Color([ 255, 0, 0 ]), 0.1), // 颜色 1 // 像素 ),
				new dojo.Color([ 255, 0, 0, 1 ]) // 颜色和透明度
		);
	}else{
		symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, // 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
				1, // 像素
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID, // 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
						new dojo.Color([ 255, 255, 0 ]), 0.1), // 颜色 1 // 像素 ),
				new dojo.Color([ 255, 255, 0, 1 ]) // 颜色和透明度
		);
	}
	var myPoint = {
		"geometry" : {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		},
		"attributes" : data,
		"symbol" : symbol
	};
	var graphic = getcurrentGraphic(data.id, pointType);

	if (graphic == null) {
		graphic = new esri.Graphic(myPoint);
		graphic.symbol = symbol;
		graphic.attributes = data;
		graphic.pointType = pointType;

		map.graphics.add(graphic);
		
	} else {
		var geometry = graphic.geometry;
		geometry.x = data.longitude;
		geometry.y = data.latitude;

		graphic.attributes = data;
		graphic.pointType = pointType;
		graphic.setGeometry(geometry);
		graphic.setSymbol(symbol);
	}
//	map.centerAndZoom(graphic.geometry, map.getLevel());
	if(pointType == showFlickerPointTyp){
		graphic.show();
	}else{
		graphic.hide();
	}
	return graphic;
};

function getcurrentGraphic(data, pointType) {

	var graphics;
	graphics = map.graphics.graphics;

	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i]) {
			if (graphics[i].attributes) {
				if (graphics[i].attributes.id == data && graphics[i].pointType == pointType) {
					return graphics[i];
				}
			}
		}
	}
	return null;
};

function getcurrentGraphicByShow(data, pointType) {
	
	var graphics;
	graphics = map.graphics.graphics;
	
	var obj;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i]) {
			if (graphics[i].attributes && graphics[i].pointType == pointType) {
				if (graphics[i].attributes.id == data ) {
					var symbol = getPointSymbol("show");
					graphics[i].setSymbol(symbol);
					obj = graphics[i];
				}else{
					var symbol = getPointSymbol(pointType);
					graphics[i].setSymbol(symbol);
				}
			}
		}
	}
	return obj;
};

function delMapPoint(pointType) {
	var graphics;
	graphics = map.graphics.graphics;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i]) {
			if (graphics[i].pointType == pointType) {
				map.graphics.remove(graphics[i]);
			}
		}
	}
};

function showMapPoint() {
	var graphics;
	graphics = map.graphics.graphics;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i]) {
			if (graphics[i].pointType == showPointType || graphics[i].pointType == showFlickerPointTyp) {
				graphics[i].show();
			}else if(graphics[i].pointType == hidePointType || graphics[i].pointType == hideFlickerPointTyp){
				graphics[i].hide();
			}
		}
	}
};

function changeType(type){
	if(type == 'report'){
		showPointType = reportPointType;
		showFlickerPointTyp = reportFlickerPointType;
		hidePointType = registerPointType;
		hideFlickerPointTyp = registerFlickerPointType;
	}else{
		showPointType = registerPointType;
		showFlickerPointTyp = registerFlickerPointType;
		hidePointType = reportPointType;
		hideFlickerPointTyp = reportFlickerPointType;
	}
	showMapPoint();
	setTimeout(function(){
		mapReSize();
	},100);
	
}

function mapReSize(){
	var mapDivHeight = $("#sbsjytbDiv").height() >= $("#slsjytbDiv").height() ? $("#sbsjytbDiv").height() - $("#sbsjySearchDiv").height() : $("#slsjytbDiv").height() - $("#slsjySearchDiv").height() ;
	mapDivHeight = mapDivHeight+22;
	
	if(mapDivHeight < 200){
		mapDivHeight = 300;
	}
	
	console.log('sbsjytbDiv:'+$("#sbsjytbDiv").height());
	console.log('slsjytbDiv:'+$("#slsjytbDiv").height());
	console.log('DivHeight:'+mapDivHeight);
	
	$("#map").height(mapDivHeight);
	
}

//2.5D的显示隐藏
$("#mapTransfer").on("click",function(){
	if (dynamicTowPointFiveD) {
		if ($("#mapTransfer").html() == "2.5D隐藏") {
			dynamicTowPointFiveD.hide();
			$("#mapTransfer").html("2.5D显示");
		} else {
			dynamicTowPointFiveD.show();
			$("#mapTransfer").html("2.5D隐藏");
		}

	}
});
$(function() {
	$(window).resize(function(){
		mapReSize();
	});
});

function initPage(){
	// 1 初始化分页信息
	initEventPage();
	initEventDealPage();
	$("#detailsShow").show();
	$('#myTabs a[href="#tab_init"]').tab('show');
	MessageSocketForEventReport();
}
function getProcedure2(data, id) {
	$("#identify2").val(data.eventId);
	$("#reportContent2").val(data.reportContent);
	$("#reportMemo2").val(data.reportMemo);
	$("#reportAccTime2").val(
			moment(data.reportAccTime).format('YYYY/MM/DD HH:mm'));

	if (data.reportUser) {
		$("#reportUser2").val(data.reportUserName);
		$("#reportUserPhone2").val(data.reportUserPhone);
	}

	$("#reportImgAdress2").attr("src", rootPath + "/" + data.reportImgAdress);

	$("#reportAdress2").val(data.reportAdress);

	if (data.gridName){
		$("#reportEventToNetGrid2").val(data.gridName);
	}else{
		$("#reportEventToNetGrid2").val('');
	}
		

	if (data.reportEventVariable){
		$("#reportEventVariable2").val(data.reportEventVariableTitle);
	}else{
		$("#reportEventVariable2").val('');
	}
		

	if (data.reportEventAttrVariable){
		$("#reportEventAttrVariable2").val(data.reportEventAttrVariable.id);
	}else{
		$("#reportEventAttrVariable2").val("");
	}
		
	if (data.reportEventType){
		$("#reportEventType2").val(data.eventName);
	}else{
		$("#reportEventType2").val('');
	}
		
	$("#procedureB2").empty();
	$.ajax({
		url : rootPath + '/ui/eventReport/getProcedure/' + id,
		dataType : 'json',
		type : 'get',
		success : function(result) {
			if (result.code == 1) {
				var list = result.data.procedures;
				$.each(list, function() {
					var tr = $("<tr align='center'></tr>");
					var opTd = $("<td>" + this.eventTaskOperate + "</td>");
					var stateTd = $("<td>" + this.eventTaskState.title
							+ "</td>");
					var timeTd = $("<td>"
							+ moment(this.eventTaskTime).format(
									"YYYY/MM/DD HH:mm") + "</td>");
					var userTd = $("<td>" + this.eventTaskUser.name + "</td>");
					$("#procedureB2").append(tr).append(opTd).append(stateTd)
							.append(timeTd).append(userTd);
				});
			}
		}
	})
	$("#procedureBB2").empty();
	$.ajax({
		url : rootPath + '/ui/eventReport/getTransfer/' + id,
		dataType : 'json',
		type : 'get',
		success : function(result) {
			if (result.code == 1) {
				var list = result.data.procedures;
				$.each(list, function() {
					var tr = $("<tr></tr>");
					var opTd = $("<td>" + this.eventTaskMemo + "</td>");
					var stateTd = $("<td>" + this.eventTaskOperate
							+ "</td>");
					var timeTd = $("<td>"
							+ moment(this.eventTaskTime).format(
							"YYYY/MM/DD HH:mm") + "</td>");
					var userTd = $("<td>" + this.eventTaskUser.name + "</td>");
					$("#procedureBB2").append(tr).append(opTd).append(stateTd)
					.append(timeTd).append(userTd);
				});
			}
		}
	})
	$("#detailsShow2").show();
};
function getProcedure(id) {
	$("#procedureB").empty();
	$.ajax({
		url : rootPath + '/ui/eventReport/getProcedure/' + id,
		dataType : 'json',
		type : 'get',
		success : function(result) {
			if (result.code == 1) {
				var list = result.data.procedures;
				$.each(list, function() {
					var tr = $("<tr></tr>");
					var opTd = $("<td>" + this.eventTaskOperate + "</td>");
					var stateTd = $("<td>" + this.eventTaskState.title
							+ "</td>");
					var timeTd = $("<td>"
							+ moment(this.eventTaskTime).format(
									"YYYY/MM/DD HH:mm") + "</td>");
					var userTd = $("<td>" + this.eventTaskUser.name + "</td>");
					$("#procedureB").append(tr).append(opTd).append(stateTd)
							.append(timeTd).append(userTd);
				});
			}
		}
	})

	$("#procedureBB").empty();
	$.ajax({
		url : rootPath + '/ui/eventReport/getTransfer/' + id,
		dataType : 'json',
		type : 'get',
		success : function(result) {
			if (result.code == 1) {
				var list = result.data.procedures;
				$.each(list, function() {
					var tr = $("<tr></tr>");
					var opTd = $("<td>" + this.eventTaskMemo + "</td>");
					var stateTd = $("<td>" + this.eventTaskOperate
							+ "</td>");
					var timeTd = $("<td>"
							+ moment(this.eventTaskTime).format(
							"YYYY/MM/DD HH:mm") + "</td>");
					var userTd = $("<td>" + this.eventTaskUser.name + "</td>");
					$("#procedureBB").append(tr).append(opTd).append(stateTd)
					.append(timeTd).append(userTd);
				});
			}
		}
	})
	// $("#detailsShow").show();
};
$("#sbsjyLi").on("click", function() {
	/*
	 * $("#tabcontentdiv").empty();
	 * $('#tabcontentdiv').html($("#sbsjyDiv").html());
	 */
	/*
	 * $("#tabcontentdiv1").show(); $('#tabcontentdiv2').hide();
	 */
	$("#detailsShow2").hide();
	$("#detailsShow").show();

});
$("#slsjyLi").on("click", function() {
	/*
	 * $("#tabcontentdiv1").hide(); $('#tabcontentdiv2').show();
	 */
	$("#detailsShow").hide();
	$("#detailsShow2").show();

});
$("#reportImgAdress").error(function() {
	$(this).attr("src", "../img/nopicture.png");
	$(this).error = null;
});
var level;
var serverData = {};
var serverDataDeal = {};
var serverTable;
var serverTableDeal;
// 8 撤销查询
jQuery('.resetBtnLeft').on('click', function() {
	jQuery('#searchLeft').val('');
	serverData.key = '';
	serverTable.draw();
});
jQuery('.resetBtnRight').on('click', function() {
	jQuery('#searchRight').val('');
	serverDataDeal.key = '';
	serverTableDeal.draw();
});
// 7 点击查询按钮
$(".searchBtnLeft").click(function() {
	serverData.key = jQuery("#searchLeft").val();
	serverTable.draw();
});
$(".searchBtnRight").click(function() {
	serverDataDeal.key = jQuery("#searchRight").val();
	serverTableDeal.draw();
});
function dealEventRegister(data) {
	window.location = window.rootPath + '/ui/eventRegister?eventReportId='
			+ data.eventId;
}
// 6 点击编辑按钮打开模态框
function dealModule(data) {
	// jQuery('#eventReportModal').modal('show');
	$("#identify").val(data.id);
	$("#reportContent").val(data.reportContent);
	$("#reportMemo").val(data.reportMemo);
	$("#reportAccTime").val(
			moment(data.reportAccTime).format('YYYY/MM/DD HH:mm'));

	if (data.reportUser) {
		$("#reportUser").val(data.reportUser.name);
		$("#reportUserPhone").val(data.reportUser.contactType);
	}

	$("#reportImgAdress").attr("src", rootPath + "/" + data.reportImgAdress);

	$("#reportAdress").val(data.reportAdress);
	
	if(data.reportEventOrg){
		$("#reportEventOrg").val(data.reportEventOrg.title);
	}else{
		$("#reportEventOrg").val("");
	}

	if (data.reportEventToNetGrid){
		$("#reportEventToNetGrid").val(data.reportEventToNetGrid.gridName);
	}else{
		$("#reportEventToNetGrid").val('');
	}
		

	if (data.reportEventVariable){
		$("#reportEventVariable").val(data.reportEventVariable.title);	
	}else{
		$("#reportEventVariable").val('');
	}
		

	if (data.reportEventAttrVariable)
		$("#reportEventAttrVariable").val(data.reportEventAttrVariable.id);
	if (data.reportEventType){
		$("#reportEventType").val(data.reportEventType.eventName);
	}else{
		$("#reportEventType").val('');
	}
		
	$("#detailsShow").show();
	
	//填充对比事件信息
	$("#ylTime").val(
			moment(data.reportAccTime).format('YYYY/MM/DD HH:mm'));

	if (data.reportUser) {
		$("#ylUser").val(data.reportUser.name);
		$("#ylPhone").val(data.reportUser.contactType);
	}

	$("#ylImg").attr("src", rootPath + "/" + data.reportImgAdress);

	$("#ylAdress").val(data.reportAdress);

	if (data.reportEventToNetGrid)
		$("#ylGrid").val(data.reportEventToNetGrid.gridName);

	
	if (data.reportEventType)
		$("#ylType").val(data.reportEventType.eventName);
};
// 点击完结按钮完结事件上报
$(".finishBtn").click(function() {
	var id = $("#identify").val();
	if (id == '') {
		alert("尚未选择上报事件源!");
		return false;
	}

	var data = {
		"id" : $("#identify").val(),
		"finishMemo" : $("#finishMemo").val(),
		"reportEventAttrVariable" : $("#reportEventAttrVariable").val()
	}
	$.ajax({
		url : rootPath + "/ui/eventReport/finishEventReport",
		dataType : 'json',
		data : JSON.stringify(data),
		type : 'post',
		contentType : "application/json",
		success : function(result) {
			if (result.data.code <= 0) {
				message("完结失败！");
			} else {
				message("完结成功！")
			}
			jQuery('#eventReportModal').modal('hide');
			serverTable.draw(false);
			serverTableDeal.draw(false);
		}
	});
});

function getEventReport(data) {
	$.ajax({
		url : rootPath + "/ui/eventReport/findById/"+data.id,
		dataType : 'json',
		data : '',
		type : 'post',
		contentType : "application/json",
		success : function(result) {
			dealModule(result.data.info);
		}
	});
};
// 点击受理事件上报按钮
$(".dealDetailBtn").click(
		function() {
			if ($("#identify").val() == "") {
				alert("请选择受理事件!");
				return false;
			}
			window.location = window.rootPath
					+ '/ui/eventRegister?eventReportIdentify='
					+ $("#identify").val();
		});

// 3 点击添加按钮弹出模态框
$(".addBtnLeft").click(function() {
	jQuery('#eventReportModal').modal('show');
});
// 1 初始化上报事件分页信息
function initEventPage() {

	serverTable = jQuery('#eventReportTable')
			.DataTable(
					{
						"serverSide" : true,
						"ordering" : false,
						"ajax" : {
							"dataType" : "json",
							"type" : "get",
							"cache" : false,
							"url" : window.rootPath
									+ '/ui/eventReport/getpage/' + "初始化",
							"data" : function(d) {
								return $.extend({}, d, serverData);
							}
						},
						columns : [
								{
									data : null,
									defaultContent : ""
								},
								{
									data : null,
									defaultContent : "",
									render : function(data, type, full, meta) {
										var operate = '<button type="button" class="btn btn-sm btn-info dealBtn" title="处理"><i class="fa fa-edit"></i></button>';
										/*
										 * + '<button type="button" class="btn
										 * btn-sm btn-info rejBtn" title="拒绝"><i
										 * class="fa fa-remove"></i></button>' + '<button
										 * type="button" class="btn btn-sm
										 * btn-danger finNode" title="完结"><i
										 * class="fa fa-unlock"></i></button>';
										 */
										return operate;
									}
								},
								{
//									data : 'reportEventType.eventName'
									data : 'reportEventTypeName'
								},
								{
									data : 'reportContent',
									render : function(data, type, full, meta) {
										if (data == null || data == undefined
												|| data == "") {
											return data;
										} else {
											return (data.length > 10) ? '<font title="'
													+ data
													+ '">'
													+ data.substring(0, 10)
													+ '...' + '</font>'
													: data;
										}
									}
								},
								{
									data : 'reportAccTime',
									render : function(data, type, full, meta) {
										if (data)
											return moment(data).format(
													'YYYY/MM/DD HH:mm');
										else
											return '';
									}
								},
								{
//									data : 'reportUser.name'
									data : 'reportUserName'
								},
								{
									data : 'reportAdress',
									render : function(data, type, full, meta) {
										if (data == null || data == undefined
												|| data == "") {
											return data;
										} else {
											return (data.length > 10) ? '<font title="'
													+ data
													+ '">'
													+ data.substring(0, 10)
													+ '...' + '</font>'
													: data;
										}
									}
								},
								{
//									data : 'reportEventOrg.title'
									data : 'reportEventOrgTitle'
								} /*
									 * , { data : "reportImgAdress", render :
									 * function(data, type, full, meta) { if
									 * (data == null || data == undefined ||
									 * data == "") { return data; } else {
									 * return '<img width="50%" src="' +
									 * window.rootPath + "/" + data + '" />'; } }
									 *  }
									 */
						],
						"drawCallback" : function(oSettings) {
							var k = 0;
							var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
							
							delMapPoint(reportPointType);
							delMapPoint(reportFlickerPointType);
							
							for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
								$('td:eq(0)',oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
								
								var data = serverTable.row(k).data();
								addToMap(data,'report');
								
								k++;
							}
							
							mapReSize();
							
							serverTable.off('click', 'tr');
							serverTable.on('click','tr',
								function(event) {
									event = event || window.event;
									var target = event.target
											|| event.scrElement;
									var data = serverTable.row(this).data();

									console.log("table callback");
									
									
									/*
									 * if (target.className
									 * .indexOf('fa-remove') != -1 ||
									 * target.className
									 * .indexOf('rejBtn') != -1) { //
									 * 拒绝 deleteGridById(data); }
									 */

									if (target.className.indexOf('fa-edit') != -1|| target.className.indexOf('dealBtn') != -1) {
										// 3 编辑
										getEventReport(data);
										getProcedure(data.id);
										$("#chongfuId").val(data.id);
									}
									/*
									 * if (target.className
									 * .indexOf('fa-sign-in') != -1 ||
									 * target.className
									 * .indexOf('addNode') != -1) {
									 * bindNode(data); } if
									 * (target.className
									 * .indexOf('fa-unlock') != -1 ||
									 * target.className
									 * .indexOf('removeNode') != -1) {
									 * 
									 * unbindNode(data); }
									 */
									if ($(this).hasClass('selected')) {
										$(this).removeClass('selected');
									} else {
										serverTable.$('tr.selected').removeClass('selected');
										$(this).addClass('selected');
										setCenter(data);
									}
									return;
								}
							);
						}
					});

};

function addToMap(data,type){
	var pointType;
	var flickerPointType;
	if(type == 'report'){
		pointType = reportPointType;
		flickerPointType = reportFlickerPointType;
	}else{
		pointType = registerPointType;
		flickerPointType = registerFlickerPointType;
	}
	
	//map加点
	var iconAddress = "";
	if (data.reportEventTypeIconAddress && data.reportEventTypeIconAddress != "") {
		iconAddress = window.rootPath + "/"+ data.reportEventTypeIconAddress;
	};
	var graphicFlicker = createFlickerPoint(data,flickerPointType);
	//map.graphics.add(graphicFlicker);
	var graphic = createPoint(data, iconAddress, pointType);
	//map.graphics.add(graphic);
}
// 1 事件受理分页信息
function initEventDealPage() {

	serverTableDeal = jQuery('#eventReportDealTable')
			.DataTable(
					{
						"serverSide" : true,
						"ordering" : false,
						"ajax" : {
							"dataType" : "json",
							"type" : "get",
							"cache" : false,
							"url" : window.rootPath
									+ '/ui/eventReport/getpagebyview/' + "已受理",
							"data" : function(d) {
								return $.extend({}, d, serverDataDeal);
							}
						},
						columns : [
								{
									data : null,
									defaultContent : ""
								},
								{
									data : null,
									defaultContent : "",
									render : function(data, type, full, meta) {
										var operate = '<button type="button" class="btn btn-sm btn-info dealExtBtn" title="处理"><i class="fa fa-edit"></i></button>';
										return operate;
									}
								},
								{
									data : 'eventName'
								},
								{
									data : 'reportContent',
									render : function(data, type, full, meta) {
										if (data == null || data == undefined
												|| data == "") {
											return data;
										} else {
											return (data.length > 10) ? '<font title="'
													+ data
													+ '">'
													+ data.substring(0, 10)
													+ '...' + '</font>'
													: data;
										}
									}
								},
								{
									data : 'eventTaskUserName'
								},
								{
									data : 'eventTaskTime',
									render : function(data, type, full, meta) {
										if (data)
											return moment(data).format(
													'YYYY/MM/DD HH:mm');
										else
											return '';
									}
								},
								{
									data : 'reportUserName'
								},
								{
									data : 'reportAccTime',
									render : function(data, type, full, meta) {
										if (data)
											return moment(data).format(
													'YYYY/MM/DD HH:mm');
										else
											return '';
									}
								},
								{
									data : 'reportAdress',
									render : function(data, type, full, meta) {
										if (data == null || data == undefined
												|| data == "") {
											return data;
										} else {
											return (data.length > 10) ? '<font title="'
													+ data
													+ '">'
													+ data.substring(0, 10)
													+ '...' + '</font>'
													: data;
										}
									}
								}, {
									data : 'gridName'
								}/*
									 * , { data : "reportImgAdress", render :
									 * function(data, type, full, meta) { if
									 * (data == null || data == undefined ||
									 * data == "") { return data; } else {
									 * return '<img width="50%" src="' +
									 * window.rootPath + "/" + data + '" />'; } }
									 *  }
									 */, {
									data : 'eventTaskStateTitle'
								}
								/*,
								{
									data : 'reportEventOrg'
								}*/

						],
						"drawCallback" : function(oSettings) {
							var k = 0;
							var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
							
							delMapPoint(registerPointType);
							delMapPoint(registerFlickerPointType);
							
							for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
								$('td:eq(0)',oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
								
								
								var data = serverTableDeal.row(k).data();
								addToMap(data,'register');
								
								k++;
							}
							
							mapReSize();
							
							serverTableDeal.off('click', 'tr');
							serverTableDeal.on('click', 'tr', function(event) {
								event = event || window.event;
								var target = event.target || event.scrElement;
								var data = serverTableDeal.row(this).data();
								getProcedure2(data, data.eventId);
								setCenter(data);
								if (target.className.indexOf('fa-edit') != -1 || target.className.indexOf('dealExtBtn') != -1) {
									// 3 编辑登记事件
									dealEventRegister(data);
								}
								return;
							});
						}
					});

};
function MessageSocketForEventReport() {
	var socket;
	if (typeof (WebSocket) == "undefined") {
		console.log("您的浏览器不支持WebSocket");
	} else {
		console.log("您的浏览器支持WebSocket");
	}
	socket = new WebSocket("ws" + window.location.origin.substring(4)
			+ "/wcsi/wcsi-websocket/" + $("#userId").val() + "/eventReport");
	// 打开事件
	socket.onopen = function() {
		console.log("Socket 已打开");
		// socket.send("这是来自客户端的消息" + location.href + new Date());
	};
	// 获得消息事件
	socket.onmessage = function(msg) {
		console.log(msg.data);
		var message = JSON.parse(msg.data);

		if (message.refreahEventReport != undefined
				&& message.refreahEventReport == "true") {
			serverTable.draw();
		}
	};
	/*
	 * //关闭事件 socket.onclose = function() { console.log("Socket已关闭"); };
	 */
	// 发生了错误事件
	socket.onerror = function() {
		//alert("Socket发生了错误");
		console.log("Socket发生了错误"); 
	}
	$(window).unload(function() {
		socket.close();
	});
};


////////////////初始化模型的树结构/////////////////////////
var modalSetting = {
	data : {
		simpleData : {
			enable : true,
			idKey : "id",
			pIdKey : "parentId",
			rootParentId : 0
		}
	},
	view : {
		showLine : true
	},
	callback : {
		onNodeCreated : zTreeOnNodeCreated
	}

};
// 设置tree图标大小
function zTreeOnNodeCreated(event, treeId, treeNode) {
	if (treeNode.type != "folder") {
		$('#' + treeNode.tId + '_ico').css( "background", "url('" + treeNode.icon + "') center center/16px 16px no-repeat");
	}
}

//事件源转办
$(".zhuanbanbtn").on('click',function() {
	var reportId = $("#identify").val();
	if (reportId == '' || reportId == null || reportId == undefined) {
		alert("请选择上报的事件源");
		return false;
	}
	jQuery('#oldEventType').val(reportId);
	jQuery("#eventTreeModal").modal('show');
	// 初始化 层级树
	var primaryNode = [];
	var url = window.rootPath + '/ui/eventReport/getAllNodes';
	jQuery.ajax({
		url : url,
		cache : false,
		type : "get",
		data : '',
		dataType : "json",
		contentType : 'application/json;charset=utf-8',// 解决返回数据中的中文乱码问题
		success : function(data) {
			primaryNode.push({
				id : 0,
				name : "事件层级",
				open : "true",
				icon : defaultEventIcon
			// iconSkin:"diy03"
			});
			for (var i = 0; i < data.nodes.length; i++) {
				if (data.nodes[i].iconAddress != undefined
						&& data.nodes[i].iconAddress != "") {
					data.nodes[i].icon = window.rootPath + "/"
							+ data.nodes[i].iconAddress;
				} else {
					data.nodes[i].icon = defaultEventIcon;
				}
				primaryNode.push(data.nodes[i]);
			}

			$.fn.zTree.init($("#eventTree"), modalSetting,
					primaryNode);

			var treeObj = $.fn.zTree.getZTreeObj("eventTree");
			var node = treeObj.getNodeByParam("id", $(
					"#registerEventType").val(), null);
			treeObj.selectNode(node);
			treeObj.expandNode(node, true, true, true);
		}
	});
});

$(".zhuanbanbtn2").on('click',function() {
	var reportId = $("#identify2").val();
	if (reportId == '' || reportId == null || reportId == undefined) {
		alert("请选择上报的事件源");
		return false;
	}
	jQuery('#oldEventType').val(reportId);
	jQuery("#eventTreeModal").modal('show');
	// 初始化 层级树
	var primaryNode = [];
	var url = window.rootPath + '/ui/eventReport/getAllNodes';
	jQuery.ajax({
		url : url,
		cache : false,
		type : "get",
		data : '',
		dataType : "json",
		contentType : 'application/json;charset=utf-8',// 解决返回数据中的中文乱码问题
		success : function(data) {
			primaryNode.push({
				id : 0,
				name : "事件层级",
				open : "true",
				icon : defaultEventIcon
				// iconSkin:"diy03"
			});
			for (var i = 0; i < data.nodes.length; i++) {
				if (data.nodes[i].iconAddress != undefined
						&& data.nodes[i].iconAddress != "") {
					data.nodes[i].icon = window.rootPath + "/"
					+ data.nodes[i].iconAddress;
				} else {
					data.nodes[i].icon = defaultEventIcon;
				}
				primaryNode.push(data.nodes[i]);
			}
			
			$.fn.zTree.init($("#eventTree"), modalSetting,
					primaryNode);
			
			var treeObj = $.fn.zTree.getZTreeObj("eventTree");
			var node = treeObj.getNodeByParam("id", $(
			"#registerEventType").val(), null);
			treeObj.selectNode(node);
			treeObj.expandNode(node, true, true, true);
		}
	});
});

$(".eventTypeConfirmBtn").on('click',function() {
	var treeObj = $.fn.zTree.getZTreeObj("eventTree");
	var selectNodes = treeObj.getSelectedNodes(treeObj);
	if (selectNodes) {
		var selectNode = selectNodes[0];
		if (selectNode) {
			var realEventType = selectNode.id;
			var reportId = $("#oldEventType").val();
			jQuery("#eventTreeModal").modal('hide');
			$.ajax({
				url : rootPath+ "/ui/eventReport/transfer/"+realEventType+"/"+reportId,
				dataType : 'json',
				type : 'POST',
				contentType : "application/json",
				success : function(result) {
					serverTable.draw(false);
					serverTableDeal.draw(false);
					message(result.msg);
//					location.reload();
				}
			});
		} else {
			message("请选择事件类型");
		}
	} else {
		message("请选择事件类型");
	}

});

$(document).on('mouseenter','img',function(){
	var type = $(this).attr('data-type');
	if(type == 'page'){
		$($(this).attr('data-div')).append("<p id='pic'><img src='"+this.src+"' id='pic1'></p>");
		$("img").mousemove(function(e){
			$("#pic").css({
//	            "top":'calc(50% - 300px)',
//	            "left":'calc(50% - 300px)'
				"top":$(document).scrollTop()+100+'px',
                "left":"calc(50% - 300px)"
	        }).fadeIn("fast");
		});
	}
});

$(document).on('mouseleave','img',function(){
	var type = $(this).attr('data-type');
	if(type == 'page'){
		$("#pic").remove();
	}
});